import 'dart:convert';

import 'package:creatures_world/framework/ext_dart/map_ext.dart';
import 'package:creatures_world/net/taxon_service.dart';
import 'package:creatures_world/pages/base/base_controller.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

import '../../db/db_helper.dart';

class SpeciesDetailController extends BaseController {
  dynamic taxonTypeDetail; //物种类别
  late Map<String, dynamic> taxon; //类别数据
  var taxonData = <String, dynamic>{}.obs; //类别详情
  var isFavor = false.obs;

  @override
  void onInit() {
    super.onInit();

    if (Get.arguments.containsKey("detail")) {
      taxonData.value = Get.arguments["detail"];
      taxon = taxonData.value;
    } else {
      taxonTypeDetail = Get.arguments["data"];
      taxon = taxonTypeDetail["taxon"];
      loadTaxonDetail();
    }
    isFavorThis();
    debugPrint("--");
  }

  loadTaxonDetail() {
    TaxonService.getSpeciesDetail(taxon!.nn2("id").toString()).then((response) {
      if (response.isOk()) {
        taxonData.value = response.data_list[0];
        debugPrint("--");
      }
      // taxon_photos；
    });
  }

  Future<void> favor() async {
    if (null != taxon) {
      String name = taxon.nn("preferred_common_name");
      int spid = taxon["id"];
      if (await DBHelper.isExistFavor(spid) == true) {
        DBHelper.deleteBySpid(spid);
      } else {
        DBHelper.insertDb(spid, name, json.encode(taxon));
      }
    }

    isFavorThis();
  }

  isFavorThis() {
    DBHelper.isExistFavor(taxon["id"]).then((v) {
      isFavor.value = v;
    });
  }
}
